<template>
	<div>
		<el-card>
			<el-form :model="state.pageParam.param" label-width="120" ref="queryFormRef" @keyup.enter.native="loadList">
			    <el-row>
			        <el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
			            <el-form-item prop="type" label="设置类型">
                            <DicSelect v-model="state.pageParam.param.type" placeholder="请选设置类型" dicCode="DASHBOARD-SET-TYPE" style="width:100%"></DicSelect>
                        </el-form-item>
                    </el-col>
			        <el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
                        <el-form-item prop="typeId" label="名称">
                            <el-input v-model="state.pageParam.param.typeId" placeholder="用户姓名、岗位名称、角色名称、机构名称" clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
                        <el-form-item prop="dashboardId" label="看板">
                            <el-select v-model="state.pageParam.param.dashboardId" clearable placeholder="请选择看板" style="width: 100%">
                                <el-option :label="item.name" :value="item.id" v-for="item in state.dashboardList" :key="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
			</el-form>
            <div class="btnSearchStyle">
                <el-button type="primary" class="ml7" @click="loadList">
                    <el-icon>
                        <ele-Search />
                    </el-icon>
                    查询
                </el-button>
                <el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
                    <el-icon>
                        <ele-Refresh />
                    </el-icon>
                    重置
                </el-button>
            </div>
        </el-card>
        <el-card>
            <div class="btnStyle">
                <el-button  type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
            </div>
            <el-table :data="state.dataList" style="width: 100%">
                <el-table-column prop="type" header-align="center" align="center" label="设置类型" column-key="DASHBOARD-SET-TYPE" :formatter="formatStatus"/>
                <el-table-column v-if="state.pageParam.param.type === '1'" prop="staffName" header-align="center" align="center" label="用户"/>
                <el-table-column v-if="state.pageParam.param.type === '2'" prop="stationName" header-align="center" align="center" label="岗位"/>
                <el-table-column v-if="state.pageParam.param.type === '3'" prop="roleName" header-align="center" align="center" label="角色"/>
                <el-table-column v-if="state.pageParam.param.type === '4' || state.pageParam.param.type === '5'" prop="orgName" header-align="center" align="center" label="机构"/>
                <el-table-column prop="dashboardId" header-align="center" align="center" label="仪表盘" :formatter="formatType"/>
                <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
                    <template #default="scope">
                        <el-button type="primary" link  @click="updateHandle(scope.row)" >修改</el-button>
                        <el-button type="primary" link  @click="deleteHandle(scope.row.id)"  >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onHandleSizeChange"
                @current-change="onHandleCurrentChange"
                :pager-count="5"
                :page-sizes="[10, 50, 200]"
                v-model:current-page="state.pageParam.page"
                background
                v-model:page-size="state.pageParam.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="state.total" small>
            </el-pagination>
        </el-card>
        <el-dialog :close-on-click-modal="false" :title="!state.submitForm.id ? '新增' : '修改'" ref="addOrUpdate" v-model="state.addOrUpdateVisible">
            <el-form :model="state.submitForm" :rules="state.submitFormRule" ref="ruleFormRef" @keyup.enter.native="dataFormSubmit(ruleFormRef)" label-width="120px">
                <el-form-item label="设置类型" prop="type">
                    <DicSelect v-model="state.submitForm.type" placeholder="请选设置类型" dicCode="DASHBOARD-SET-TYPE" style="width:100%"></DicSelect>
                </el-form-item>
                <el-form-item v-if="state.submitForm.type === '1'" label="用户选择" prop="typeId">
                    <el-select-v2
                        v-model="state.submitForm.typeId"
                        style="width: 100%"
                        filterable
                        remote
                        :remote-method="queryUserByName"
                        clearable
                        :options="state.userOptions"
                        :loading="state.typeIdLoading"
                        placeholder="输入姓名查询"
                    />
                </el-form-item>
                <el-form-item v-if="state.submitForm.type === '2'" label="岗位选择" prop="typeId">
                    <el-tree-select v-model="state.submitForm.typeId" value-key="id" :data="state.stationOptions" :props="stationProps" style="width: 100%">
                    </el-tree-select>
                </el-form-item>
                <el-form-item v-if="state.submitForm.type === '3'" label="角色选择" prop="typeId">
                    <el-select-v2
                        v-model="state.submitForm.typeId"
                        :options="state.roleOptions"
                        placeholder="选择角色"
                        style="width: 100%"
                    />
                </el-form-item>
                <el-form-item v-if="state.submitForm.type === '4'" label="角色机构" prop="typeId">
                    <OrgSelect v-model="state.submitForm.typeId" placeholder="组织机构" :tenantId="userInfos.tenantId"></OrgSelect>
                </el-form-item>
                <el-form-item label="仪表盘" prop="dashboardId">
                    <el-select v-model="state.submitForm.dashboardId" clearable placeholder="请选择看板" style="width: 100%">
                        <el-option :label="item.name" :value="item.id" v-for="item in state.dashboardList" :key="item.id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="state.addOrUpdateVisible = false">取消</el-button>
                    <el-button type="primary" @click="dataFormSubmit(ruleFormRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts" name="sysDashboardSetting">
import { ElMessage, ElMessageBox, FormInstance, ElLoading } from 'element-plus'
import { ref, reactive, onMounted, watch, defineAsyncComponent } from 'vue'
import { systemApi } from '/@/api/sys/system-api'
//引入组件
const OrgSelect = defineAsyncComponent(() => import('/@/components/orgSelect/index.vue'))
import { getDataDictionaryList } from '/@/utils/cacheDic'
import { reportApi, DashboardPage } from '/@/api/sys/report-api'
import { useUserInfo } from '/@/stores/userInfo'
import { storeToRefs } from 'pinia'
const { userInfos } = storeToRefs(useUserInfo())
const queryFormRef = ref<FormInstance>()
const ruleFormRef = ref<FormInstance>()
interface ListItem {
  value: string
  label: string
}
const stationProps = {
    label: 'orgName',
    children: 'children',
}
const state = reactive({
    listLoading: false,
    total: 0,
    dataList: [],
    dataListSelections: [],
    dataDictionaryList: {} as any,
    pageParam: {
        page: 1,
        pageSize: 10,
        param: {
            id: '',
            type: '1',
            dashboardId: '',
            typeId: '',
            createUser: '',
            createTime: '',
            modUser: '',
            modTime: '',
            tenantId: '',
        }
    },
    addOrUpdateVisible: false,
    submitForm: {
            id: '',
            type: '',
            dashboardId: '',
            typeId: '',
            createUser: '',
            createTime: '',
            modUser: '',
            modTime: '',
            tenantId: '',
    },
    submitFormRule: {
            type: [
                { required: true, message: '设置类型不能为空', trigger: 'blur' }
            ],
            dashboardId: [
                { required: true, message: '请选择看板', trigger: 'blur' }
            ],
            typeId: [
                { required: true, message: '类型对应不能为空', trigger: 'blur' }
            ],
    },
    dashboardList: [] as DashboardPage[],
    typeIdLoading: false,
    userOptions: [] as ListItem[],
    stationOptions: [],
    roleOptions: [] as ListItem[],
})
const loadList = () => {
    state.listLoading = true
    systemApi.querySysDashboardSettingListPage(state.pageParam).then(data => {
        if (data && data.code === 0) {
            state.dataList = data.data.records
            state.total = data.data.totalRow
        } else {
            state.dataList = []
            state.total = 0
        }
    }).catch(() => {
    }).finally(() => {
        state.listLoading = false
    })
}
const getStationTree = () =>{
    systemApi.getUserStationTreeByTenant(userInfos.value.tenantId).then(data => {
      if (data && data.code === 0) {
        state.stationOptions = data.data
      }
    })
}

const getTenantRoleList = () =>{
    systemApi.getTenantRoleList().then(data => {
      if (data && data.code === 0) {
        state.roleOptions = data.data.map((item: any) => {
            return { value: item.id, label: item.roleName }
        })
      }
    })
}
// 页面加载时
onMounted(() => {
    // 数据字典
	getDataDictionaryList(state.dataDictionaryList, ['DASHBOARD-SET-TYPE'])
    getStationTree()
    getTenantRoleList()
    reportApi.getDashboardList().then(data => {
        if (data && data.code === 0) {
            state.dashboardList = data.data
        }
    }).finally(() => {
        // 列表查询
        loadList()
    })
})
watch(() => state.pageParam.param.type, (val:string) =>{
    loadList()
})
//重置
const reSetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    state.pageParam.page = 1
    loadList()
}
// 分页改变
const onHandleSizeChange = (val: number) => {
    state.pageParam.pageSize = val;
    loadList()
}
// 分页改变
const onHandleCurrentChange = (val: number) => {
    state.pageParam.page = val;
    loadList()
}
//删除
const deleteHandle = (id: string | undefined) => {
    if(!id) {
        ElMessage.error('请选择记录！')
        return
    }
    ElMessageBox.confirm('是否确定删除所选记录', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(() => {
        systemApi.deleteSysDashboardSettingInfo(id).then(data => {
            if (data && data.code === 0) {
                ElMessage.success('删除成功')
                loadList()
            } else {
                ElMessage.error(data.message)
            }
        }).catch(() => {
            ElMessage.error("删除失败")
        })
    })
}
//打开新增弹窗
const addOrUpdateHandle = () => {
    state.submitForm = {
            id: '',
            type: '',
            dashboardId: '',
            typeId: '',
            createUser: '',
            createTime: '',
            modUser: '',
            modTime: '',
            tenantId: '',
    }
    state.addOrUpdateVisible = true
}
//打开修改弹窗
const updateHandle = (row: any | undefined) => {
    state.submitForm = {
            id: row.id,
            type: row.type,
            dashboardId: row.dashboardId,
            typeId: row.typeId,
            createUser: row.createUser,
            createTime: row.createTime,
            modUser: row.modUser,
            modTime: row.modTime,
            tenantId: row.tenantId,
    }
    state.addOrUpdateVisible = true
}
//新增修改提交
const dataFormSubmit = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid: boolean) => {
        if (valid) {
            //提交数据
            const loading = ElLoading.service({
                lock: true,
                text: '处理中',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            if(!state.submitForm.id) {
                //新增
                systemApi.saveSysDashboardSettingInfo(state.submitForm).then(data => {
                    if (data && data.code === 0) {
                        ElMessage.success('保存成功')
                        state.addOrUpdateVisible = false
                        loadList()
                    } else {
                        ElMessage.error(data.message)
                    }
                }).catch(() => {
                    ElMessage.error('保存失败')
                }).finally(() => {
                    loading.close()
                })
            }else{
                systemApi.updateSysDashboardSettingInfo(state.submitForm).then(data => {
                    if (data && data.code === 0) {
                        ElMessage.success('保存成功')
                        state.addOrUpdateVisible = false
                        loadList()
                    } else {
                        ElMessage.error(data.message)
                    }
                }).catch(() => {
                    ElMessage.error('保存失败')
                }).finally(() => {
                    loading.close()
                })
            }
        }
    })
}
const queryUserByName = (query: string) => {
  if (query !== '') {
    state.typeIdLoading = true
    systemApi.queryUserByName({
        page: 1,
        pageSize: 200,
        param: {
            staffName: query,
        }
    }).then(data => {
        if (data && data.code === 0) {
            state.userOptions = data.data.map((item: any) => {
                return { value: item.id, label: item.staffName }
            })
        } else {
            state.userOptions = []
        }
        
    }).catch(() => {
    }).finally(() => {
        state.typeIdLoading = false
    })
  } else {
    state.userOptions = []
  }
}
const formatType = (row: any, column: any, cellValue: string | number, index: number) => {
	if(Object.keys(state.dashboardList).length>0){
		if (cellValue) {
			return state.dashboardList.filter((item) => {
                return item.id === cellValue
            })[0].name
		}
	}
}

const formatStatus = (row: any, column: any, cellValue: string | number, index: number) => {
	if(Object.keys(state.dataDictionaryList).length>0){
		if (cellValue) {
			return state.dataDictionaryList[column.columnKey].get(cellValue);
		}
	}
}
</script>